from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
import os
from django.http import JsonResponse
from functions import models
import datetime
import json
from django.shortcuts import HttpResponse
from django.db.models import F

# 接收搜索框发来的信息
class Search_functions(APIView):
    def post(self, request, *args, **kwargs):
        uploaded_file = request.FILES['file']  # 获取上传的文件
        filename_with_extension = uploaded_file.name  # 获取文件完整名称
        filename, file_extension = os.path.splitext(filename_with_extension)  # 分解文件名
        print(file_extension)
        if file_extension == '.docx':
            file_extension = '/images/resource/DOC.png'
            filetype = 101  # 1代表.docx类型文件
            return JsonResponse({'filetype': filetype})

class loginview(APIView):
        def post(self,request,*args,**kwargs):
            username = request.data['username']
            password = request.data['password']
            myobject = models.user.objects.create(username=username,password=password)
            print(request.data)
            print(myobject.userID)
            return JsonResponse({"status":myobject.userID})#返回一个字典

class addfile(APIView):#获取文件后的数据库操作
    def post(self,request,*args,**kwargs):
            print(request.data)
            select = [0, 0, 0, 0, 0]
            if request.data['selectmath']:
                select[0] = 1
            if request.data['selecteng']:
                select[1] = 1
            if request.data['selectzz']:
                select[2] = 1
            if request.data['selecteng']:
                select[3] = 1
            if request.data['selectother']:
                select[4] = 1

            resourcename = request.data['name']
            userID = request.data['userID']
            sectionID = ''.join(map(str,select))

            datetimes = datetime.datetime.now()
            print(datetimes,sectionID,userID,resourcename)
            myobject = models.resource.objects.create(title=resourcename,userID=userID,datetime=datetimes,sectionID=sectionID,downloads='0')
            print(resourcename)
            return Response({"status":True})#返回一个字典

class getfile(APIView):#小程序初始化后的文件列表
    def todict(self,file:models.resource):
        return {
            'num':file.id,
            'name': file.title,
            'pv':file.downloads
        }
    def post(self, request,  *args, **kwargs):
            # section = request.data['section']
            # print('section',section)
            filelist = models.resource.objects.all()
            li = []
            for i in filelist:
                print(self.todict(i))
                li.append(self.todict(i))
            array = [{'num':5,'name':'高等数学','pv':100},
                     {'num':2,'name':'数学','pv':10},
                     {'num':3,'name':'英语','pv':100},
                     {'num':4,'name':'高等数学','pv':100}]
            print(request.data)
            lij = json.dumps(li)
            print(lij)
            return HttpResponse(lij)

class searchfile(APIView):#接受搜索框数据，返回文件信息列表
    def todict(self,file:models.resource):
        return {
            'num':file.id,
            'name': file.title,
            'pv':file.downloads
        }
    def post(self, request, *args, **kwargs):
        print(request.data)
        filename = request.data['inputContent']
        filename=filename
        filelist = models.resource.objects.filter(title__icontains=filename)
        li = []

        for i in filelist:
            print(self.todict(i))
            li.append(self.todict(i))
        array = [{'num': 5, 'name': '高等数学', 'pv': 100},
                 {'num': 2, 'name': '数学', 'pv': 10},
                 {'num': 3, 'name': '英语', 'pv': 100},
                 {'num': 4, 'name': '高等数学', 'pv': 100}]
        lij = json.dumps(li)
        print(lij)
        return HttpResponse(lij)
class downloadfile(APIView):
    def post(self, request, *args, **kwargs):
        print(request.data)
        userID = request.data['userID']
        filenum = request.data['filenum']
        filelist = models.resource.objects.filter(id=filenum).update(downloads=F('downloads') + 1)
        history = models.history.objects.create(userID=userID, resourceID=filenum,datetime=datetime.datetime.now())
        #根据filenum在数据库中找对应的文件名字 时间  传回前端 新建array 传回去自增显示
        return HttpResponse('kong')


class comment(APIView):
    def todict(self, data):
        return {
            'title': data.title,
            'contentID':data.id,
            'likes': data.likes,
            'userID':data.userID
        }
    def post(self, request, *args, **kwargs):
        print(request.data)
        sectionID = request.data['sectionID']
        if sectionID == 4:
            ass = models.comment.objects.all()
        else:
            ass = models.comment.objects.filter(sectionID=sectionID)
        li = []
        for i in ass:
            li.append(self.todict(i))
        lij = json.dumps(li)
        print(lij)
        return HttpResponse(lij)
class writecomment(APIView):
    def post(self,request,*args,**kwargs):
        train = {
            '数学':1,
            '外语':2,
            '政治':3,
            '综合':4
        }
        print(request.data)
        title = request.data['title']
        userID = request.data['userID']
        sectionID = request.data['sectionID']
        print(title)
        datetimes = datetime.datetime.now()
        comment = models.comment.objects.create(userID=userID,title=title,datetime=datetimes,sectionID=sectionID)
        return HttpResponse('chenggong')

class history(APIView):
    def todict(self,file:models.resource,history):
        return {
            'num':file.id,
            'name': file.title,
            'pv':file.downloads,
            'datetimes': history.datetime.isoformat()
        }

    def post(self,request,*args,**kwargs):
        print(request.data)
        ass = models.history.objects.filter(userID=request.data['userID'])
        li = []
        for i in ass:
            print(i.resourceID)
            ass1 = models.resource.objects.filter(id=i.resourceID)
            print(i.datetime.isoformat())
            li.append(self.todict(ass1[0],i))
        lij = json.dumps(li)
        print(lij)
        return HttpResponse(lij)